﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using RFDeviceNet;

namespace RFDeviceTester
{
    class PacketWorker
    {
        private Socket _soc;
        private IPEndPoint _localIpe;
        private ConnectionInfo _connection;

        public PacketWorker()
        {
            _connection = new ConnectionInfo();
            _soc = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            _soc.ReceiveTimeout = 2000;
            _localIpe = new IPEndPoint(IPAddress.Any, 6001);
            _soc.Bind(_localIpe);
            /*_soc.BeginReceive(_connection.Buffer, 0, _connection.Buffer.Length, SocketFlags.Broadcast, On_Receive,
                              _connection);*/
        }

        public _UDP_DEVINFOBLOCK_PC_Net GetUdpPcketFrom620()
        {
            var count = _soc.Receive(_connection.Buffer);
            var mas = new byte[count];
            Buffer.BlockCopy(_connection.Buffer, 0, mas, 0, count);
            var block = GetBlock(mas);
            return block;
        }

        private void On_Receive(IAsyncResult ar)
        {
            var con = ar.AsyncState as ConnectionInfo;
            var count = con.Socket.EndReceive(ar);
            var mas = new byte[count];
            Buffer.BlockCopy(con.Buffer, 0, mas, 0, count);
            var block = GetBlock(mas);
        }

        private _UDP_DEVINFOBLOCK_PC_Net GetBlock(byte[] mas)
        {
            if (mas.Length != 268)
            {
                throw new Exception("wrong packet length");
            }
            var block = new _UDP_DEVINFOBLOCK_PC_Net();
            var devTypeBuf = new byte[2];
            Buffer.BlockCopy(mas, 0, devTypeBuf, 0, 2);
            block.DeviceType = BitConverter.ToUInt16(devTypeBuf, 0);
            Buffer.BlockCopy(mas, 2, block.IP, 0, 4);
            Buffer.BlockCopy(mas, 6, block.MAC, 0, 4);
            Buffer.BlockCopy(mas, 10, block.Info, 0, 256);
            return block;
            return new _UDP_DEVINFOBLOCK_PC_Net();
        }

        class ConnectionInfo
        {
            public ConnectionInfo()
            {
                Buffer = new byte[1000];
            }

            public Byte[] Buffer { get; set; }
            public Socket Socket { get; set; }
        }
    }
}
